import { Layout,theme } from 'antd';
import {Routes,Route, Navigate,useLocation} from 'react-router-dom'
import menus from '@/router/menus'
import {Fragment} from 'react'
import NotFound from '@/views/notfound/Index'
import { useSelector } from 'react-redux';
import {getCheckedKeysArr,getPermissionMenus} from '@/utils/permissionMenus'
const { Content } = Layout;


// 判断当前的路径是否在menus中存在   pathname='/banner/home'
function isContainMenus(menus,pathname){
  return menus.some(item=>{
    if(item.children){
      if(item.key === pathname){
        return true
      }else{
        // return item.children.some(other=>{
        //   console.log('111111111111111111111111111',other,pathname)
        //   return other.key === pathname
        // })
        return isContainMenus(item.children,pathname)
      }
    }else{
      return item.key === pathname
    }
  })
}


export default function AppMain() {
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  

  // 递归遍历生成多个Route
  const renderRoute = (menus)=>{
    return menus.map(item=>{   
      if(item.children){
        if(item.index){ // 如果有index属性的，就认为默认跳转到此路由
          return <Fragment key={item.key}>
            <Route index element={<Navigate to={item.key}/>}></Route>
            <Route key={item.key} path={item.key} element={item.element}>
              {renderRoute(item.children)}
            </Route>
          </Fragment>
        }
        return <Route key={item.key} path={item.key} element={item.element}>
          {renderRoute(item.children)}
        </Route>
      }else{
        if(item.index){
          return <Fragment key={item.key}>
            <Route index element={<Navigate to={item.key}/>} />
            <Route key={item.key} path={item.key} element={item.element}></Route>
          </Fragment>
        }
        return <Route key={item.key} path={item.key} element={item.element}></Route>
      }
    })
  }


  // 左侧导航权限实现
  const checkedKeys = useSelector(state=>state.admin.checkedKeys)
  const adminname = useSelector(state=>state.admin.adminname)
  let newMenus = []
  if(checkedKeys.length === 0 && adminname === 'admin'){ // 如果是超级管理员，直接给所有查询权限的方式
    newMenus = menus
  }else{
    // 获取所有的keys数组
    const newCheckedKeys = getCheckedKeysArr(checkedKeys)
    // 从menus导航中根据keys数组进行筛选导航
    newMenus = getPermissionMenus(menus,newCheckedKeys)
  }

  const {pathname} = useLocation()
  const flag = isContainMenus(menus,pathname)  // flag为真的话，代表当前的路由在总的menus路由表中是存在的
  return (
    <Content
      style={{
        margin: '24px 16px',
        padding: 24,
        minHeight: 280,
        background: colorBgContainer,
      }}
    >
      <Routes>
        {renderRoute(newMenus)}
        <Route path='*' element={flag ? <div>暂无权限...</div> : <NotFound/>}/>
      </Routes>
    </Content>
  )
}
